<template>
    <div class="register-page">
        <!--        导航栏-->
        <div class="register-top">
            <div class="logo">
                <span class="logo-span" @click="$router.push('/')">芬 享</span>
                <span class="logo-text">众享你的喜悦!</span>
            </div>
            <div class="register-tip hidden-md-and-down">
                <span>已有芬享账号?</span>
                <el-button size="mini" type="warning" @click.native="$router.push('/login')">登录</el-button>
            </div>
        </div>


        <!--        注册表单-->
        <div class="register-main">
            <el-row>
                <el-col :span="12">
                    <!--注册表单-->
                    <el-form ref="form" :rules="rules" :model="form" label-width="80px">
                        <el-form-item label="创建账号" style="width: 400px" prop="account">
                            <el-input v-model="form.account"></el-input>
                        </el-form-item>

                        <el-form-item label="创建密码" style="width: 400px" prop="password">
                            <el-input v-model="form.password" show-password></el-input>
                        </el-form-item>

                        <el-form-item label="确认密码" style="width: 400px" prop="checkPassword">
                            <el-input v-model="form.checkPassword" show-password></el-input>
                        </el-form-item>

                        <el-form-item label="选择角色" style="width: 400px" class="hidden-md-and-up">
                            <el-select v-model="form.role" placeholder="请选择角色">
                                <el-option
                                        v-for="(item,index) in baseRole"
                                        :key="index"
                                        :label="item.roleName"
                                        :value="item.roleId">
                                </el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="验证码" prop="code">
                            <div class="register-code-box">
                                <el-input v-model="form.code" class="code-input"></el-input>
                                <img class="code-img"
                                     @click="getCaptchaImage"
                                     :src="imgSrc" alt="点击刷新验证码">
                            </div>
                        </el-form-item>

                        <el-form-item>
                            <el-button type="warning" style="width: 320px" @click="registerBtn">完成注册</el-button>
                        </el-form-item>

                        <el-form-item>
                            <el-checkbox v-model="agreement" class="register-radio">
                                <div class="text"> 我已阅读并同意《芬享用户协议》《隐私政策》 ，
                                    并授权芬享使用该芬享账号信息（如昵称、头像、个人信息等）进行统一管理
                                </div>
                            </el-checkbox>
                        </el-form-item>


                    </el-form>


                </el-col>
                <!--                角色选择-->
                <el-col :span="12" class="hidden-md-and-down">
                    <h2 class="register-role-h2">选择角色</h2>

                    <div class="register-roles">

                        <!--         角色-->
                        <div class="role-box" @click="checkRole(role,index)" :class="{active:index===curRole}"
                             v-for="(role,index) in baseRole"
                             :key="index">
                            <el-avatar :size="100" :src="role.defaultAvatar"/>
                            <div class="role-name">
                                {{role.roleName}}
                            </div>
                            <div class="role-desc">
                                {{role.remark}}
                            </div>
                        </div>

                    </div>
                </el-col>
            </el-row>
        </div>

    </div>
</template>

<script>
    import {getCaptchaImage} from "@/api/common/captchaImage"
    import {getBaseRole, checkUserExist} from "@/api/common/common"
    import {register} from "@/api/business/user"


    export default {
        name: 'Register',
        data() {
            let validateAccount = async (rule, value, callback) => {
                let patt = /^[a-zA-Z0-9_-]{10,20}$/g
                if (value === '') {
                    callback(new Error('请设置用户账号'))
                } else if (!patt.test(value)) {
                    callback(new Error('10到20位纯数字'))
                } else {
                    let res = await checkUserExist({account: value.trim()})
                    if (res.data) {
                        callback("用户账号已存在，请重新设置")
                    } else {
                        callback()
                    }
                }
            }
            //密码校验
            let validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'))
                } else {
                    if (this.form.password !== '') {
                        this.$refs.form.validateField('checkPass')
                    }
                    callback()
                }
            }
            let validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'))
                } else if (value !== this.form.password) {
                    callback(new Error('两次输入密码不一致!'))
                } else {
                    callback()
                }
            }
            return {
                imgSrc: "",
                baseRole: [],
                curRole: 0,
                agreement: false,
                form: {
                    account: "",
                    password: "",
                    checkPassword: "",
                    role: 1,//默认食客
                    code: "",
                    uuid: "",
                },
                rules: {
                    account: [
                        {validator: validateAccount, trigger: 'blur'},
                        {required: true, message: '请设置账号', trigger: 'blur'},
                    ],
                    password: [
                        {required: true, message: '请设置密码', trigger: 'blur'},
                        {min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'},
                        {validator: validatePass, trigger: 'blur'}
                    ],
                    checkPassword: [
                        {required: true, message: '请确认密码', trigger: 'blur'},
                        {validator: validatePass2, trigger: 'blur'}
                    ],
                    role: [
                        {required: true, message: '请选择用户角色', trigger: 'change'}
                    ],
                    code: [
                        {required: true, message: '请输入验证码', trigger: 'blur'},
                    ],
                },
            }
        },
        methods: {
            /**
             * 点击注册
             */
            registerBtn() {

                this.$refs.form.validate((valid) => {
                    if (valid) {
                        /**
                         * 判断有没有勾选阅读事项
                         */
                        if (!this.agreement) {
                            this.msgWarn("您是否同意《服务协议》和《隐私政策》")
                            return;
                        }
                        register(this.form).then(res => {
                            this.msgSuccess("注册成功!")
                            //情况表单
                            this.resetForm("form")
                            this.$store.dispatch("registerAndLogin", res.token).then(() => {
                                this.$router.push('/')
                            })
                        }).catch(() => {
                            this.msgError("注册失败")
                        })

                    } else {
                        this.msgError('请填写完整信息')
                        return false
                    }
                })
            },
            /**
             * 获取验证码
             */
            getCaptchaImage() {
                getCaptchaImage().then(res => {
                    this.form.uuid = res.uuid
                    this.imgSrc = "data:image/gif;base64," + res.img
                })
            },
            /**
             * 获取默认角色
             */
            getBaseRoles() {
                getBaseRole().then(res => {
                    this.baseRole = res.data
                })
            },
            /**
             * 选择角色
             */
            checkRole(role, index) {
                this.msgWarn("你选择了 " + role.roleName + " 这个角色")
                this.curRole = index
                this.form.role = role.roleId
            }
        },
        created() {
            this.getCaptchaImage()
            this.getBaseRoles()
        },
        components: {}
    }
</script>

<style scoped lang='less'>
    .register-page {
        margin-bottom: 100px;

        .register-top {
            display: flex;
            height: 70px;
            width: 100%;
            align-items: center;
            justify-content: space-between;
            padding: 0 10vw;
            border-bottom: 2px solid #D8D8D8;


            .logo {
                .logo-span {
                    padding: 15px 10px;
                    background-color: rgb(255, 195, 0);
                    border-radius: 15px;
                    font-size: 13px;
                    font-weight: 700;
                    cursor: pointer;
                    margin-right: 10px;
                }

                .logo-text {
                    color: #E6A23C;
                    font-size: 15px;
                }
            }

            .register-tip {
                > span {
                    font-size: 13px;
                    color: #909399;
                    margin-right: 25px;
                }
            }
        }


        .register-main {

            padding: 4vw 8vw 0 8vw;

            .register-radio {
                display: flex;

                .text {
                    width: 320px;
                    line-height: 20px;
                    white-space: normal;
                    word-break: break-all;
                    word-wrap: break-word;
                }
            }

            .register-code-box {
                display: flex;
                width: 480px;

                .code-input {
                    width: 150px;
                }

                .code-img {
                    cursor: pointer;
                    margin-left: 10px;
                    height: 60px;
                    width: 160px;
                }
            }


            .register-role-h2 {
                font-weight: 700;
                font-size: 20px;
                margin-bottom: 30px;
                color: #E6A23C;
            }

            .register-roles {
                display: flex;
                justify-content: space-between;

                .active {
                    border: 2px solid rgb(255, 195, 0) !important;
                    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
                }

                .role-box:hover {
                    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
                }

                .role-box {
                    border: 2px solid transparent;
                    width: 32%;
                    text-align: center;
                    padding: 20px;
                    cursor: pointer;

                    .role-name {
                        margin: 10px 0;
                        font-size: 14px;
                        color: #E6A23C;

                    }

                    .role-desc {
                        font-size: 14px;
                        white-space: normal;
                        word-break: break-all;
                        word-wrap: break-word;
                        color: #909399;
                        line-height: 20px;
                    }
                }
            }

        }

    }

</style>
